import { defineStore } from 'pinia';
import { 
  fetchCartItems, 
  addCartItem, 
  updateCartItem, 
  removeCartItem 
} from '@/api/cartService.js';

export const useCartStore = defineStore('cart', {
    state: () => ({
      cartItems: []
    }),
  actions: {
    // 获取购物车商品项
    async fetchCart(userId) {
      this.isLoading = true;
      try {
        this.cartItems  = await fetchCartItems(userId);

        console.log('获取购物车成功:', this.cartItems);
      } catch (error) {
        console.error('获取购物车失败:', error);
      } finally {
        this.isLoading = false;
      }
    },
    // 添加商品到购物车
    async addItemToCart(userId, item) {
      try {
        const response = await addCartItem(userId, item);
        this.cartItems.push(response.data);
      } catch (error) {
        console.error('添加商品到购物车失败:', error);
      }
    },
    // 更新购物车商品项
    async updateCartItem(cartItemId, updateData) {
      try {
        const response = await updateCartItem(cartItemId, updateData);
        const index = this.cartItems.findIndex(item => item.id === cartItemId);
        if (index !== -1) {
          this.cartItems[index] = { ...this.cartItems[index], ...response.data };
        }
      } catch (error) {
        console.error('更新购物车商品项失败:', error);
      }
    },
    // 移除购物车商品项
    async removeCartItem(cartItemId) {
      try {
        await removeCartItem(cartItemId);
        this.cartItems = this.cartItems.filter(item => item.id !== cartItemId);
      } catch (error) {
        console.error('移除购物车商品项失败:', error);
      }
    }
  },
  getters: {
    // 计算购物车总价
    totalPrice: (state) => {
      return state.cartItems.reduce((total, item) => {
        return total + (item.listPrice * item.quantity);
      }, 0);
    },
    // 获取购物车商品总数
    totalQuantity: (state) => {
      return state.cartItems.reduce((total, item) => {
        return total + item.quantity;
      }, 0);
    }
  }
});